/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DebateFrame2.java
 *
 * Created on 19 avr. 2012, 00:51:05
 */
package debate.gui;

import debate.game.HandStatus;
import debate.move.Accept;
import debate.move.Argue;
import debate.move.Assert;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;

/**
 *
 * @author julien
 */
public class DebateFrameNew extends javax.swing.JFrame {

    private HandStatus status;

    /*************************/
    /*                       */
    /*     BUILDER           */
    /*                       */
    /*************************/
    public DebateFrameNew() {

        initComponents();
        status = HandStatus.NoOneHasHand;

        // Listener sur le bouton de début de partie
        refereePane.getNewGameButton().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                startGame();
            }
        });

        // Listener sur les boutons de prise de main
        player1Pane.getTakeHandjButton().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                // Selon le status on prend ou on rend la main
                if (status == HandStatus.NoOneHasHand) {
                    status = HandStatus.PlayerOneHasHand;
                    player2Pane.getTimer().stop();
                    updateDisplay(status);
                } else {
                    status = HandStatus.NoOneHasHand;
                    updateDisplay(status);
                    player2Pane.getTimer().start();
                }
            }
        });
        player2Pane.getTakeHandjButton().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                // Selon le status on prend ou on rend la main
                if (status == HandStatus.NoOneHasHand) {
                    status = HandStatus.PlayerTwoHasHand;
                    updateDisplay(status);
                    player1Pane.getTimer().stop();
                } else {
                    status = HandStatus.NoOneHasHand;
                    updateDisplay(status);
                    player1Pane.getTimer().start();
                }
            }
        });

        //Listener sur les boutons de coup
        defineMovesHandlers();
        // Fonctions de prise en main par appui sur une touche
        final String onQPressed = "onQpressed";
        final String onMPressed = "onMpressed";
        InputMap inputMap = this.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        inputMap.put(KeyStroke.getKeyStroke("Q"), onQPressed);
        inputMap.put(KeyStroke.getKeyStroke("M"), onMPressed);
        ActionMap actionMap = this.getRootPane().getActionMap();
        actionMap.put(onQPressed,
                new AbstractAction() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        player1Pane.getTakeHandjButton().doClick();
                    }
                });
        actionMap.put(onMPressed,
                new AbstractAction() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        player2Pane.getTakeHandjButton().doClick();
                    }
                });


        // Mise à jour des boutons
        updateDisplay(HandStatus.NoOneHasHand);

    }

    /*************************/
    /*                       */
    /*     METHODS           */
    /*                       */
    /*************************/
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        player1Pane = new debate.gui.PlayerPane();
        player2Pane = new debate.gui.PlayerPane();
        refereePane = new debate.gui.RefereePane();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        player1Pane.setName("player1Pane"); // NOI18N

        player2Pane.setName("player2Pane"); // NOI18N

        refereePane.setName("refereePane"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(player1Pane, javax.swing.GroupLayout.PREFERRED_SIZE, 439, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(refereePane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(player2Pane, javax.swing.GroupLayout.PREFERRED_SIZE, 439, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(refereePane, javax.swing.GroupLayout.PREFERRED_SIZE, 546, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(player2Pane, javax.swing.GroupLayout.PREFERRED_SIZE, 546, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(player1Pane, javax.swing.GroupLayout.PREFERRED_SIZE, 546, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void startGame() {
        if (!player1Pane.getReady()) {
            JOptionPane.showMessageDialog(this, "Player 1 absent", "Expected 2 players", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (!player2Pane.getReady()) {
            JOptionPane.showMessageDialog(this, "Player 2 absent", "Expected 2 players", JOptionPane.ERROR_MESSAGE);
            return;

        }
        player1Pane.startTimer();
        player1Pane.getTakeHandjButton().setEnabled(true);
        player1Pane.setBuzzerGreen();

        player2Pane.startTimer();
        player2Pane.getTakeHandjButton().setEnabled(true);
        player2Pane.setBuzzerGreen();

        // Placer ici pour éviter que les joueurs ne puissent buzzer avant
        // que la partie ait effectivement débuté

        refereePane.getNewGameButton().setEnabled(false);

    }

    public void defineMovesHandlers() {
        // Listener Ajout de Formule
        player1Pane.getAssertButton().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                Assert.assertFormula(player1Pane.getPlayer(), player2Pane.getPlayer(), refereePane.getReferee());
                player1Pane.refreshModel();
                player2Pane.refreshModel();
            }
        });
        player2Pane.getAssertButton().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                Assert.assertFormula(player2Pane.getPlayer(), player1Pane.getPlayer(), refereePane.getReferee());
                player1Pane.refreshModel();
                player2Pane.refreshModel();
            }
        });

        // Listener Accept Formule
        player1Pane.getAcceptButton().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                Accept.accept(player1Pane.getPlayer(), player2Pane.getPlayer(), refereePane.getReferee(), player1Pane.getSelectedRequest());
                player1Pane.refreshModel();
                player2Pane.refreshModel();
                refereePane.refreshModel();
            }
        });
        player2Pane.getAcceptButton().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                Accept.accept(player2Pane.getPlayer(), player1Pane.getPlayer(), refereePane.getReferee(), player2Pane.getSelectedRequest());
                player1Pane.refreshModel();
                player2Pane.refreshModel();
                refereePane.refreshModel();
            }
        });

        // Listener Argue
        player1Pane.getArgueButton().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                Argue argueMove = new Argue();
                argueMove.newArgue(player1Pane.getPlayer(), player2Pane.getPlayer(), refereePane.getReferee());
                player1Pane.refreshModel();
                player2Pane.refreshModel();
                refereePane.refreshModel();
            }
        });
        player2Pane.getArgueButton().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                Argue argueMove = new Argue();
                argueMove.newArgue(player2Pane.getPlayer(), player1Pane.getPlayer(), refereePane.getReferee());
                player1Pane.refreshModel();
                player2Pane.refreshModel();
                refereePane.refreshModel();
            }
        });
    }

    public void updateDisplay(HandStatus status) {
        switch (status) {
            case NoOneHasHand: {
                player1Pane.updateDisplay(false, false);
                player2Pane.updateDisplay(false, false);
                break;
            }
            case PlayerOneHasHand: {
                player1Pane.updateDisplay(true, true);
                player2Pane.updateDisplay(false, true);
                break;
            }
            case PlayerTwoHasHand: {
                player1Pane.updateDisplay(false, true);
                player2Pane.updateDisplay(true, true);
                break;
            }
        }
    }

    public void actualizeTable(ArrayList<String> s) {
//        for (String c : s) {
//            playerPane1.getPlayer().getFormulaList().add(c);
//            playerPane1.getjList1().setListData(playerPane1.getPlayer().getFormulaList());
//            refereePane.getReferee().getFormulaList().add(c);
//            refereePane.getjList1().setListData(refereePane.getReferee().getFormulaList());
//
//        }
    }

    /*************************/
    /*                       */
    /*     MAIN              */
    /*                       */
    /*************************/
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DebateFrameNew.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DebateFrameNew.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DebateFrameNew.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DebateFrameNew.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new DebateFrameNew().setVisible(true);
            }
        });
    }
    /*************************/
    /*                       */
    /*     VARIABLES         */
    /*                       */
    /*************************/
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private debate.gui.PlayerPane player1Pane;
    private debate.gui.PlayerPane player2Pane;
    private debate.gui.RefereePane refereePane;
    // End of variables declaration//GEN-END:variables
}
